package com.java.netty.nio.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Author: Dgg
 * @Date: 2022/1/24 22:05
 */
public class MyClinetHandler extends SimpleChannelInboundHandler<MessageProtoCol> {
	private int count;

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, MessageProtoCol msg) throws Exception {
		int len = msg.getLen();
		byte[] content = msg.getBytes();

		System.out.println("客户端接收到消息 如下");
		System.out.println("长度：" + len);
		System.out.println("内容：" + new String(content, Charset.forName("UTF-8")));
		System.out.println("客户端消息数量" + ++this.count);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//使用客户端 发送十次数据
		for (int i = 0; i < 5; i++) {
			String msg = new String("今天天气冷吃火锅");
			byte[] bytes = msg.getBytes(StandardCharsets.UTF_8);
			int length = msg.getBytes(CharsetUtil.UTF_8).length;

			//创建协议包对象
			MessageProtoCol messageProtoCol = new MessageProtoCol();
			messageProtoCol.setLen(length);
			messageProtoCol.setBytes(bytes);
			ctx.writeAndFlush(messageProtoCol);
		}

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

}
